﻿using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using NetTopologySuite.GeometriesGraph;

namespace NetTopologySuite.Operation.Relate
{
	public class EdgeEndBuilder
	{
		public IList<EdgeEnd> ComputeEdgeEnds(IEnumerable<Edge> edges)
		{
			IList<EdgeEnd> list = new List<EdgeEnd>();
			foreach (Edge edge in edges)
			{
				this.ComputeEdgeEnds(edge, list);
			}
			return list;
		}

		public void ComputeEdgeEnds(Edge edge, IList<EdgeEnd> l)
		{
			EdgeIntersectionList edgeIntersectionList = edge.EdgeIntersectionList;
			edgeIntersectionList.AddEndpoints();
			IEnumerator<EdgeIntersection> enumerator = edgeIntersectionList.GetEnumerator();
			EdgeIntersection edgeIntersection = null;
			if (!enumerator.MoveNext())
			{
				return;
			}
			EdgeIntersection edgeIntersection2 = enumerator.Current;
			do
			{
				EdgeIntersection eiPrev = edgeIntersection;
				edgeIntersection = edgeIntersection2;
				edgeIntersection2 = null;
				if (enumerator.MoveNext())
				{
					edgeIntersection2 = enumerator.Current;
				}
				if (edgeIntersection != null)
				{
					this.CreateEdgeEndForPrev(edge, l, edgeIntersection, eiPrev);
					this.CreateEdgeEndForNext(edge, l, edgeIntersection, edgeIntersection2);
				}
			}
			while (edgeIntersection != null);
		}

		public void CreateEdgeEndForPrev(Edge edge, IList<EdgeEnd> l, EdgeIntersection eiCurr, EdgeIntersection eiPrev)
		{
			int num = eiCurr.SegmentIndex;
			if (eiCurr.Distance == 0.0)
			{
				if (num == 0)
				{
					return;
				}
				num--;
			}
			Coordinate coordinate = edge.GetCoordinate(num);
			if (eiPrev != null && eiPrev.SegmentIndex >= num)
			{
				coordinate = eiPrev.Coordinate;
			}
			Label label = new Label(edge.Label);
			label.Flip();
			EdgeEnd item = new EdgeEnd(edge, eiCurr.Coordinate, coordinate, label);
			l.Add(item);
		}

		public void CreateEdgeEndForNext(Edge edge, IList<EdgeEnd> l, EdgeIntersection eiCurr, EdgeIntersection eiNext)
		{
			int num = eiCurr.SegmentIndex + 1;
			if (num >= edge.NumPoints && eiNext == null)
			{
				return;
			}
			Coordinate coordinate = edge.GetCoordinate(num);
			if (eiNext != null && eiNext.SegmentIndex == eiCurr.SegmentIndex)
			{
				coordinate = eiNext.Coordinate;
			}
			EdgeEnd item = new EdgeEnd(edge, eiCurr.Coordinate, coordinate, new Label(edge.Label));
			l.Add(item);
		}
	}
}
